<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页涂鸦板</title>
</head>

<body>
    <div style="text-align: center;">
        <canvas id="cansElem">

        </canvas>
        <footer>by chenjiali<br> 2023-11-13</footer>
    </div>
    <script>
        //获得画布对象
        var canvas = document.getElementById('cansElem');
        canvas.width = 900;
        canvas.height = 600;
        canvas.style.border = '1px solid #f00';
        //准备画笔(获取上下文)
        var context = canvas.getContext('2d');
        context.lineWidth = '3';
        context.strokeStyle = '#0f0'

        //当鼠标按下触发onmousedoen事件，驱动获取鼠标起始点坐标函数
        canvas.onmousedown = function(e) {
            console.log(canvas.getBoundingClientRect());
            console.log(e.clientX, e.clientY);


            var x = e.clientX - canvas.getBoundingClientRect().left;
            var y = e.clientY - canvas.getBoundingClientRect().top;
            context.beginPath();
            context.moveTo(x, y);

            //当鼠标移动式触发onmousemove事件，驱动端点坐标的获取，进行绘制图像
            canvas.onmousemove = function(event) {
                console.log('绘图中..');



                var x = event.clientX - canvas.getBoundingClientRect().left;
                var y = event.clientY - canvas.getBoundingClientRect().top;
                context.lineTo(x, y);
                context.stroke();
            }

            //当鼠标移动式触发onmouseup事件，onmousemove函数返回null,取消端点获取
            canvas.onmouseup = function() {
                console.log('取消绘制');
                canvas.onmousemove = null;
            }
        }
    </script>
</body>

</html>